<template>
<view>
	<button type="primary" size="mini" @tap="login">一键登录</button>
</view>
</template>

<script setup>
import { reactive } from "vue";
import useUserStore from '@/store/user.js'
const userStore = useUserStore();
const userInfo = reactive({
	nickName:'',
	avatarUrl:'',
	openid:'',
})
const login=()=>{
	uni.showModal({
		title:"登录权限获取提示",
		content:"是否同意",
		success:function(res){
			if(res.confirm){
				console.log("确认")
				uni.getUserProfile({
					desc: "仅用作登录功能", //声明获取用户个人信息后的用途(必填)
					success:(user)=>{
						console.log(user) //
						userInfo.nickName=user.userInfo.nickName
						userInfo.avatarUrl=user.userInfo.avatarUrl
						uni.login({
							provider:"weixin",
							success(code) {
								console.log(code) 
								//获取openid
								uni.request({
									url:'https://api.weixin.qq.com/sns/jscode2session',
									method:"GET",
									data:{
										appid:'',
										secret:'',
										js_code:code.code,
										grant_type:'authorization_code'
									},
									success: (r) => {
										console.log(r,"res")
										userInfo.openid=r.data.openid
										//保存到pinia
										userStore.fillUser(userInfo)
										//保存到本地
										uni.setStorageSync("userInfo",userInfo)
										uni.showToast({
											title:"登录成功",
											icon:'success'
										})
										//跳转到我的页面
										uni.switchTab({
											url:'/pages/my/my'
										})
									}
								})
							}
							
						})
					}
				})
			}else if(res.cancel){
				console.log("取消")
				uni.showToast({
					title:"权限获取失败",
					icon:"none"
				})
			}
		}
	})
	
}
</script>

<style scoped>

</style>